import request from '@/utils/request';
import { SUCCESS_CODE } from '@/utils/types.d';
import type { ResponseData } from '@/utils/types.d';
import type { PackageTableItem, UpdatePkgParams } from './types.d';

export async function queryPackageList(
  params: any,
  sort: any,
): Promise<{
  success: boolean;
  total: number;
  data: PackageTableItem[];
}> {
  const res: ResponseData<{
    total: number;
    data: PackageTableItem[];
  }> = await request('/api/package-manager/v1.0.0/list', {
    method: 'GET',
    params: {
      data: params,
      sort,
    },
  });
  if (res?.code === SUCCESS_CODE)
    return { success: true, total: res.data.total, data: res.data.data };
  return { success: false, total: 0, data: [] };
}

export async function uploadPkg(form: FormData) {
  const res = await request('/api/package-manager/v1.0.0/upload', {
    method: 'POST',
    requestType: 'form',
    data: form,
  });
  if (res?.code === SUCCESS_CODE)
    return {
      data: res.data,
      success: true,
      message: '上传成功',
    };
  return { data: res?.data, success: false, message: res?.message || '上传失败' };
}
export async function updatePkg(id: string, data: UpdatePkgParams) {
  const res = await request(`/api/package-manager/v1.0.0/${id}`, {
    method: 'PUT',
    data: data,
  });
  if (res?.code === SUCCESS_CODE) return { success: true, data: res.data, message: '更新成功' };
  return { success: false, data: res?.data, message: res?.message || '更新失败' };
}

export async function delPkg(id: string) {
  const res: ResponseData<null> = await request(`/api/package-manager/v1.0.0/${id}`, {
    method: 'DELETE',
  });
  if (res?.code === SUCCESS_CODE) return { success: true, message: '删除成功' };
  return { success: false, message: res?.message || '删除失败' };
}
